﻿using Hx.ADSyncPlatform.ActiveDirectory.Model;
using Hx.ADSyncPlatform.Db;
using Hx.ADSyncPlatform.Entity.Entities;
using Hx.ADSyncPlatform.Service.Base;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Threading.Tasks;

namespace Hx.ADSyncPlatform.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class Plat_DataPermissionService : BaseService<Plat_DataPermission>
    {
        protected DbSet<Plat_DataPermission> Plat_DataPersmissionDb;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        public Plat_DataPermissionService(DbContext db):base(db)
        {
            this.Plat_DataPersmissionDb = db.DbSet<Plat_DataPermission>();
        }

        /// <summary>
        ///  根据AD 对象（用户或组）的ObjectGuid 查询数据权限
        /// </summary>
        /// <param name="objectGuid"></param>
        /// <returns></returns>
        public async Task<List<Plat_DataPermission>> GetDataPersmissionsByObjectGuid(Guid objectGuid)
        {
            List<Plat_DataPermission> dataPersmissions = await base.Query(n => n.ObjectGuid == objectGuid);

            return dataPersmissions;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchResults"></param>
        /// <param name="dataPersmissions"></param>
        /// <returns></returns>
        public IEnumerable<SearchResult> FilterOrgHandler(IEnumerable<SearchResult> searchResults, List<Plat_DataPermission> dataPersmissions)
        {
            return searchResults.Where(searchResult =>
            {
                bool filter = dataPersmissions.FindIndex(datapermission =>
                 {
                     string distinguishedName = searchResult.Properties["DistinguishedName"][0].ToString();
                     if (datapermission.Type == "all")
                     {
                         bool find = distinguishedName.EndsWith(datapermission.Dn);
                         return find;
                     }
                     else if (datapermission.Type == "half")//todo 预制组织
                     {
                         return datapermission.Dn == distinguishedName;
                     }
                     return false;
                 }) != -1;
                return filter;
            });

        }


        /// <summary>
        /// 过滤人员
        /// </summary>
        /// <param name="searchResults"></param>
        /// <param name="dataPersmissions"></param>
        /// <returns></returns>
        public IEnumerable<SearchResult> FilterObjectHandler(IEnumerable<SearchResult> searchResults, List<Plat_DataPermission> dataPersmissions, List<string> systemOus)
        {
            return searchResults.Where(searchResult =>
            {
                bool filter = dataPersmissions.FindIndex(datapermission =>
                {
                    string distinguishedName = searchResult.Properties["DistinguishedName"][0].ToString();
                    bool find = false;

                    if (datapermission.Type == "all")
                    {
                        find = distinguishedName.EndsWith(datapermission.Dn);
                    }
                    else if (datapermission.Type == "half")//todo 预制组织
                    {
                        foreach (string ou in systemOus)
                        {
                            find = distinguishedName.EndsWith($"OU={ou},{datapermission.Dn}");
                            if (find) break;
                        }

                    }
                    return find;
                }) != -1;
                return filter;
            });

        }
        /// <summary>
        ///  根据数据权限过滤组织
        /// </summary>
        /// <param name="objectGuid"></param>
        /// <returns></returns>
        public async Task<List<Organization>> FilterOrg(Guid objectGuid, List<Organization> organizations)
        {
            List<Plat_DataPermission> dataPersmissions = await base.Query(n => n.ObjectGuid == objectGuid);
            organizations = organizations.Where(org =>
            {
                return dataPersmissions.FindIndex(datapermission =>
                {
                    if (datapermission.Type == "all")
                    {
                        return org.DistinguishedName.EndsWith(datapermission.Dn);
                    }
                    else if (datapermission.Type == "half")//todo 预制组织
                    {
                        return datapermission.Dn == org.DistinguishedName;
                    }
                    return false;
                }) != -1;
            }).ToList();
            return organizations;
        }

        /// <summary>
        /// 添加数据权限
        /// </summary>
        /// <param name="objectGuid"></param>
        /// <param name="dataPersmissions"></param>
        public void AssignDataPermission(Guid objectGuid, List<Plat_DataPermission> dataPersmissions)
        {
            dbClient.Ado.BeginTran();
            try
            {
                this.Plat_DataPersmissionDb.Delete(n => n.ObjectGuid == objectGuid);

                foreach (Plat_DataPermission dataPermission in dataPersmissions)
                {
                    dataPermission.Id = Guid.NewGuid();
                    dataPermission.ObjectGuid = objectGuid;
                    this.Plat_DataPersmissionDb.Insert(dataPermission);
                }
                dbClient.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                dbClient.Ado.RollbackTran();
                throw ex;
            }



        }


        /// <summary>
        /// 删除管理员的数据数据权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteDataPermissionsByManagerGuid(Guid id)
        {
            Plat_DataPersmissionDb.Delete(n => n.ObjectGuid == id);
            return true;
        }
    }
}
